﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using UserService.Domain;
using UserService.Domain.Aggregate.User;
using Volo.Abp.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore.PostgreSql;
using Volo.Abp.Modularity;

namespace UserService.EntityFrameworkCore
{
    [DependsOn(
        typeof(UserServiceDomainModule),
        typeof(AbpEntityFrameworkCoreModule),
        typeof(AbpEntityFrameworkCorePostgreSqlModule))]
    public class UserServiceEntityFrameworkCoreModule : AbpModule
    {
        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            var services = context.Services;
            services.AddAbpDbContext<UserServiceDbContext>(options =>
            {
                options.AddDefaultRepositories(true);
                options.Entity<User>(user =>
                {
                    user.DefaultWithDetailsFunc = u => u.Include(p => p.Profile);
                });
            });

            // 配置复用连接
            Configure<AbpDbContextOptions>(options =>
            {
                options.Configure(ctx =>
                {
                    if (ctx.ExistingConnection != null)
                    {
                        ctx.DbContextOptions.UseNpgsql(ctx.ExistingConnection);
                    }
                    else
                    {
                        ctx.DbContextOptions.UseNpgsql(ctx.ConnectionString);
                    }
                });
            });
        }
    }
}